package com.rickpan.controller;

import com.rickpan.common.Result;
import com.rickpan.dto.request.ApiKeyRequest;
import com.rickpan.dto.request.ChatRequest;
import com.rickpan.dto.response.ApiKeyResponse;
import com.rickpan.dto.response.TestApiKeyResponse;
import com.rickpan.service.AIChatService;
import com.rickpan.utils.SecurityUtils;
import com.rickpan.security.JwtTokenProvider;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.nio.charset.StandardCharsets;

/**
 * AI聊天控制器
 */
@RestController
@RequestMapping("/api/ai-chat")
@Validated
@Tag(name = "AI聊天", description = "AI助手聊天功能")
public class AIChatController {

    private static final Logger log = LoggerFactory.getLogger(AIChatController.class);

    @Autowired
    private AIChatService aiChatService;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    /**
     * 发送消息给AI助手
     * @param request 聊天请求
     * @param httpRequest HTTP请求
     * @return 流式响应
     */
    @PostMapping("/send")
    @Operation(summary = "发送消息", description = "发送消息给AI助手，返回流式响应")
    public ResponseEntity<StreamingResponseBody> sendMessage(
            @RequestBody @Valid ChatRequest request,
            HttpServletRequest httpRequest) {

        try {
            // 手动验证JWT Token（因为此路径已从Spring Security中豁免）
            Long userId = validateJwtAndGetUserId(httpRequest);
            if (userId == null) {
                log.warn("Invalid or missing JWT token for AI chat request");
                return ResponseEntity.status(401).build();
            }

            log.info("User {} sending message to AI chat", userId);

            // 创建流式响应
            StreamingResponseBody stream = outputStream -> {
                try {
                    aiChatService.sendMessageStream(userId, request, outputStream);
                } catch (Exception e) {
                    log.error("Stream error for user {}: {}", userId, e.getMessage(), e);
                    try {
                        // 检查输出流是否还可用
                        if (outputStream != null) {
                            String errorMessage = "data: {\"error\":\"" + e.getMessage() + "\"}\n\n";
                            outputStream.write(errorMessage.getBytes(StandardCharsets.UTF_8));
                            outputStream.flush();
                        }
                    } catch (Exception writeError) {
                        log.error("Failed to write error message (client may have disconnected): {}", writeError.getMessage());
                    }
                }
            };

            return ResponseEntity.ok()
                    .header("Content-Type", "text/event-stream")
                    .header("Cache-Control", "no-cache")
                    .header("Connection", "keep-alive")
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Headers", "Cache-Control")
                    .body(stream);

        } catch (Exception e) {
            log.error("Error before streaming for request: {}", e.getMessage(), e);
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 保存API Key配置
     * @param request API Key请求
     * @return 操作结果
     */
    @PostMapping("/api-key")
    @Operation(summary = "保存API Key", description = "保存用户的OpenRouter API Key")
    public Result<Void> saveApiKey(@RequestBody @Valid ApiKeyRequest request) {
        Long userId = SecurityUtils.getCurrentUserId();
        log.info("User {} saving API key configuration", userId);
        
        aiChatService.saveApiKey(userId, request);
        return Result.success();
    }

    /**
     * 获取API Key配置
     * @return API Key配置信息
     */
    @GetMapping("/api-key")
    @Operation(summary = "获取API Key配置", description = "获取用户的API Key配置信息")
    public Result<ApiKeyResponse> getApiKey() {
        Long userId = SecurityUtils.getCurrentUserId();
        log.info("User {} getting API key configuration", userId);
        
        ApiKeyResponse response = aiChatService.getApiKey(userId);
        return Result.success(response);
    }

    /**
     * 测试API Key是否有效
     * @return 测试结果
     */
    @PostMapping("/api-key/test")
    @Operation(summary = "测试API Key", description = "测试API Key是否有效")
    public Result<TestApiKeyResponse> testApiKey() {
        Long userId = SecurityUtils.getCurrentUserId();
        log.info("User {} testing API key", userId);
        
        TestApiKeyResponse response = aiChatService.testApiKey(userId);
        return Result.success(response);
    }

    /**
     * 手动验证JWT Token并获取用户ID
     * 用于SSE流式传输接口的权限验证
     */
    private Long validateJwtAndGetUserId(HttpServletRequest request) {
        try {
            // 从请求头获取JWT Token
            String bearerToken = request.getHeader("Authorization");
            if (!StringUtils.hasText(bearerToken) || !bearerToken.startsWith("Bearer ")) {
                return null;
            }

            String jwt = bearerToken.substring(7);

            // 验证Token有效性
            if (!jwtTokenProvider.validateToken(jwt)) {
                return null;
            }

            // 获取用户ID
            return jwtTokenProvider.getUserIdFromToken(jwt);

        } catch (Exception e) {
            log.error("JWT validation error: {}", e.getMessage());
            return null;
        }
    }
}
